//
//  TitlePullDownButton.swift
//  test-ios
//
//  Created by wyz5204 on 2023/6/14.
//

import Foundation
import UIKit
import RxSwift
import SnapKit
import Reusable


class TitlePullDownButton : UIButton{
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    private lazy var label: UILabel = {
        let view = UILabel()
        view.text = "项目aaaaaaaaaa"
        view.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        view.textColor = UIColor.black_dark
        return view
    }()
    
    private lazy var arrowView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "project_down_icon")
        return view
    }()
    
    
    
    private lazy var orgListView : UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.delegate = self
        view.dataSource = self
        view.rowHeight = 50
        view.separatorStyle = .none
        view.backgroundColor = .white
        view.register(OrgNameTableCell.self, forCellReuseIdentifier: "org")
        return view
    }()
    
    var selected_closure: ((OrgBean) -> Void)?
    
    var modelArray: [OrgBean] = []
    
    
    func configUI() {
        self.rx.tap.asDriver().drive(onNext: { [weak self] in
            // 进行弹出
            guard let this = self else {
                return
            }
            // 进行点击事件
            this.isSelected.toggle()
            
            // 判断是否点击
            if (this.isSelected){
                this.arrowView.image = UIImage(named: "project_up_icon")
                
                // 添加UItableView 这里添加一个UIView 其大小和整个屏幕一样 并且在button 上添加一个tableView
                let backgroundView = UIButton()
                backgroundView.backgroundColor = .red.withAlphaComponent(0.05)
                backgroundView.rx.tap.asDriver().drive (onNext: {
                    this.hideDialog(backgroundView)
                }).disposed(by: this.rx.disposeBag)
                
                backgroundView.addTo(this.currentView()) { view in
                    view.snp.makeConstraints { make in
                        make.width.equalToSuperview()
                        make.height.equalToSuperview().offset(-WPSystem.screen.navigationHeight)
                        make.top.equalToSuperview().offset(WPSystem.screen.navigationHeight)
                    }
                }
                
                // 在button上添加一个tableView
                this.orgListView.addTo(backgroundView) { view in
                    view.snp.makeConstraints { make in
                        make.width.equalToSuperview()
                        make.top.equalToSuperview()
                        make.height.equalToSuperview().dividedBy(3)
                    }
                }
                
                this.loadOrgData()
            }else {
                print(" >>> \(this.orgListView.superview is UIButton)")
                this.hideDialog(this.orgListView.superview as! UIButton)
            }
        }, onDisposed: { [weak self] in
            // 进行界面的清除工作
            self?.arrowView.image = UIImage(named: "project_down_icon")
        }).disposed(by: rx.disposeBag)
        
        addSubview(label)
        addSubview(arrowView)
        
        arrowView.snp.makeConstraints { (make) in
            make.width.equalTo(13)
            make.height.equalTo(12.5)
            make.centerY.equalToSuperview().offset(-2)
            make.right.equalToSuperview()
        }
        
        label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.greaterThanOrEqualToSuperview()
            make.right.equalTo(arrowView.snp.left).offset(-20)
            make.width.lessThanOrEqualTo(SCREEN_WIDTH - 0)
        }
        // 在这进行监听即可 监听数据的变化
        registerNotificationObserver(name: RDNotification.defaultOrg) { [weak self] notifice in
            print("registerNotificationObserver >>> \(self?.hash) , \(notifice.object is OrgBean)")
            if(notifice.object is OrgBean){
                // 设置自身的显示
                self?.label.setTitleAndColor((notifice.object as! OrgBean).orgName)
            }
        }
        initData()
    }
    
    func hideDialog(_ superBt : UIButton){
        self.isSelected = false
        self.arrowView.image = UIImage(named: "project_down_icon")
       
        self.isUserInteractionEnabled = false
        UIView.animate(withDuration: 0.25) {
            superBt.backgroundColor = .red.withAlphaComponent(0.05)
        } completion: { [weak self ]_ in
            self?.isUserInteractionEnabled = true
            superBt.removeFromSuperview()
        }
    }
}

extension TitlePullDownButton : UITableViewDataSource , UITableViewDelegate {
    
    func loadOrgData(){
        // 去加载本地的组织列表
        guard let orgs = RDDBModel.shared().fetchOrgs() else {
            return
        }
        // 获取默认的组织列表
        self.modelArray = orgs
        self.orgListView.reloadData()
        // 进行数据的填充和UI的刷行
    }
    
    func initData(){
        // 去加载本地的组织列表
        guard let org = RDDBModel.shared().getDefaultOrg() else {
            self.label.setTitleAndColor("暂无组织")
            return ;
        }
        self.label.setTitleAndColor(org.orgName)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return modelArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "org", for: indexPath) as! OrgNameTableCell
        cell.initBinder(tableView , modelArray[indexPath.row] , indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let orgBean = modelArray[indexPath.row]
        print("table select \(orgBean)")
        // 进行选择默认的
        RDDBModel.shared().setDefaultOrgId(orgBean.id)
        postNotificationMessage(RDNotification.defaultOrg ,object: orgBean)
        hideDialog(tableView.superview as! UIButton)
    }
    
}
